import uuid

from django.shortcuts import render

# Create your views here.

from django.http import FileResponse, StreamingHttpResponse, HttpResponse
from rest_framework import response
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet, ReadOnlyModelViewSet

from api.models import WavFiles, Histories
from utils.generate.mandarin import generate_mandarin
from utils.generate.cantonese import generate_cantonese
from api.serializers import *
from utils.response.response import ReturnMsg


class GenerateMandarinView(APIView):
    permission_classes = [AllowAny]

    def post(self, request):
        data = request.data
        text = data.get('text')
        wav = WavFiles.objects.filter(text=text, typ=0)
        if wav:
            tmp = wav[0]
        else:
            name = generate_mandarin(text)
            name = name.split("/")[-1]
            name = "media/wav/" + name
            wav = WavFiles()
            wav.text = text
            wav.typ = 0
            wav.wav = name
            wav.save()
            tmp = wav
        if request.user.id:
            Histories.objects.get_or_create(wav_id=tmp.id, user_id=request.user.id)
        return Response({
            "url": tmp.wav
        })


class GenerateCantoneseView(APIView):
    permission_classes = [AllowAny]

    def post(self, request):
        data = request.data
        text = data.get('text')
        wav = WavFiles.objects.filter(text=text, typ=1)

        if wav:

            tmp = wav[0]
        else:
            name = generate_cantonese(text)
            name = name.split("/")[-1]
            name = "media/wav/" + name
            wav = WavFiles()
            wav.text = text
            wav.typ = 1
            wav.wav = name
            wav.save()

            tmp = wav
        if request.user.id:
            Histories.objects.get_or_create(wav_id=tmp.id, user_id=request.user.id)
        return Response({
            "url": tmp.wav
        })


# class IdentifyMandarinView(APIView):
#     permission_classes = [AllowAny]
#
#     def post(self, request):
#         data = request.data
#         file = data.get("file")
#         name = os.path.join(BASE_DIR, "files", f"{uuid.uuid4()}.wav")
#
#         with open(name, 'wb+') as destination:
#             for chunk in file.chunks():
#                 destination.write(chunk)
#
#         text = identify_mandarin(name)
#         # os.remove(name)
#         return Response({
#             "data": text
#         })


# class IdentifyCantonese(APIView):
#     permission_classes = [AllowAny]
#
#     def post(self, request):
#         data = request.data
#         file = data.get("file")
#         name = os.path.join(BASE_DIR, "files", f"{uuid.uuid4()}.wav")
#
#         with open(name, 'wb+') as destination:
#             for chunk in file.chunks():
#                 destination.write(chunk)
#
#         text = identify_cantonese(name)
#         os.remove(name)
#         return Response({
#             "data": text
#         })

class HistoryModelViewSet(ReadOnlyModelViewSet):
    serializer_class = HistoriesSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        return Histories.objects.filter(user_id=self.request.user.id)

    def list(self, request, *args, **kwargs):
        response = super().list(request, args, kwargs)
        return Response(ReturnMsg(data=response.data).dict(), status=200)

    def retrieve(self, request, *args, **kwargs):
        response = super().retrieve(request, args, kwargs)
        return Response(ReturnMsg(data=response.data).dict(), status=200)


class ClearView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request):
        user = request.user
        histories = Histories.objects.filter(user_id=user.id)
        for history in histories:
            history.delete()

        return Response(ReturnMsg(code=1, msg="清空成功", data={}).dict())
